package com.myopen.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.StrKit;
import com.myopen.config.ConstConfig;
import com.myopen.kit.DeviceKit;

public class WeixinAuthInterceptor implements Interceptor{

	@Override
	public void intercept(Invocation inv) {
		HttpServletRequest request=inv.getController().getRequest();
		
		String ignoreUrl="/weixin/auth/,/weixin/redirect/";
	
		boolean isWechat=DeviceKit.isWeChat(request);
		
		if(isWechat&&!(ignoreUrl.contains(inv.getActionKey()))) {
			//如果是微信访问
			HttpSession session=request.getSession();
			String WEIXIN_SESSION_OPEN_ID=(String)session.getAttribute(ConstConfig.WEIXIN_SESSION_OPEN_ID);
			if(StrKit.isBlank(WEIXIN_SESSION_OPEN_ID)) {
				//如果没有微信openid，那么需要跳转授权，除非当前访问的url有配置说微信访问不需要授权
				session.setAttribute(ConstConfig.GOTO_URL_SESSION_ATTRIBUTE, request.getRequestURL().toString());
				inv.getController().redirect("/weixin/auth");
			}else {
				inv.invoke();
			}
		}else {
			inv.invoke();
		}
		
	}

}
